package com.mocoop.plugin.file;


import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;

import com.mocoop.commom.MyConstants;
import com.mocoop.commom.MyOSS;
import com.mocoop.commom.PhotoUtils;
import com.mocoop.commom.MyOSS.MyOSSCallBack;
import com.mocoop.dao.AjaxWorkerDao;
import com.mocoop.dao.AjaxWorkerDaoImp;
import com.mocoop.entity.AjaxInfo.FileProgress;
import com.mocoop.photo.PhotoBrowseActivity;
import com.mocoop.plugin.MocoopPlugin;


public class FileHelper extends MocoopPlugin {
	@Override
	public boolean execute(final String action, final CordovaArgs args,
			final CallbackContext callbackContext) throws JSONException {

		cordova.getThreadPool().execute(new Runnable() {
			@Override
			public void run() {
				if ("getThumbnailImgFile".equals(action)) {
					getThumbnailImgFile(args, callbackContext);
				}else if("downloadFiles".equals(action)){
					try {
						downloadFiles(args, callbackContext);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}else if("downloadFile".equals(action)){
					try {
						downloadFile(args, callbackContext);
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}else if("PhotoBrowse".equals(action)){
//					List<Map<String,String>> list = new SyncDaoImp(getActivity(), getUserID()).execute("select * from T_ImgFilePaths", new String[0]);
					int index = 0;
					JSONArray jsonArray;
					String[] arr = null;
					try {
						jsonArray = args.getJSONArray(0);
						arr = new String[jsonArray.length()];
						for(int i=0;i<jsonArray.length();i++){
							arr[i] = jsonArray.getString(i);
						}
						index = args.getInt(1);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
					Intent intent = new Intent(getActivity(),PhotoBrowseActivity.class);
					intent.putExtra(PhotoBrowseActivity.BUNDLE_KEY_IMAGES, arr);
					intent.putExtra(PhotoBrowseActivity.BUNDLE_KEY_INDEX, index);
					getActivity().startActivity(intent);
				}
				
			}
		});
	

		return true;
	}

	private void insertImgFile(AjaxWorkerDao ajaxWorkerDao, String fileKey,
			String filePath) {
		ajaxWorkerDao
				.execute(
						"Insert Into T_ImgFilePaths ([FImgFileKey],[FImgFilePath]) values(?,?);",
						new String[] { fileKey, filePath });
	}

	public void downloadFile(CordovaArgs args,
			final CallbackContext callbackContext) throws JSONException {

	
		MyOSSCallBack myOSSCallBack = new MyOSSCallBack() {
			@Override
			public void onSuccess(boolean isOriginal, String path, Object fileName) {
				insertImgFile(new AjaxWorkerDaoImp(getActivity(), getUserID()),
						fileName.toString(), "file://"+path);
				JSONObject message = new JSONObject();
				try {
					message.put("result", true);
					message.put("filePath", "file://"+path);
					message.put("fileID", fileName.toString());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					callbackContext.success(message);
			}

			@Override
			public void onError(boolean isOriginal, String fileID, Object obj) {
					JSONObject message = new JSONObject();
					try {
						message.put("result", false);
						message.put("fileID", fileID);
						message.put("exception",obj.toString());
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
						callbackContext.success(message);
			}

			@Override
			public void onProgress(FileProgress fileProgress) {
				// TODO Auto-generated method stub
				
			}
		};
		
			MyOSS.download(args.getString(0), myOSSCallBack);
		
	}
	
	
	public void downloadFiles(CordovaArgs args,
			final CallbackContext callbackContext) throws JSONException {

		final JSONArray fileList = args.getJSONArray(0);

		MyOSSCallBack myOSSCallBack = new MyOSSCallBack() {
			private JSONArray responesArray = new JSONArray();
			@Override
			public void onSuccess(boolean isOriginal, String path, Object fileName) {
				insertImgFile(new AjaxWorkerDaoImp(getActivity(), getUserID()),
						fileName.toString(), "file://"+path);
				JSONObject message = new JSONObject();
				try {
					message.put("result", true);
					message.put("filePath", "file://"+path);
					message.put("fileID", fileName.toString());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				responesArray.put(message);
				if(responesArray.length() == fileList.length()){
					callbackContext.success(message);
				}
			}

			@Override
			public void onError(boolean isOriginal, String fileID, Object obj) {
					JSONObject message = new JSONObject();
					try {
						message.put("result", false);
						message.put("fileID", fileID);
						message.put("exception",obj.toString());
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					responesArray.put(message);
					if(responesArray.length() == fileList.length()){
						callbackContext.success(message);
					}
			}

			@Override
			public void onProgress(FileProgress fileProgress) {
				// TODO Auto-generated method stub
				
			}
		};
		for (int i = 0; i < fileList.length(); i++) {
			MyOSS.download(fileList.getString(i), myOSSCallBack);
		}
	}

	private void getThumbnailImgFile(final CordovaArgs args,
			final CallbackContext callbackContext) {
		Bitmap bm = null;
		String newPath = "";
		try {
			bm = PhotoUtils.decodeImage(args.getString(2), args.getInt(0),
					args.getInt(1));
			newPath = args.getString(2);
			String[] strs = newPath.split("/");
			String fileName = strs[strs.length - 1];
			newPath = MyConstants.getPath(getActivity(),getUserID());
			newPath += args.getInt(0) + "x" + args.getInt(1) + fileName;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		PhotoUtils.saveBitmapToFile(newPath, bm);
		callbackContext.success("file://" + newPath);
	}
}
